<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public $layout="//layouts/main";
	public function actions()
	{
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		$this->render('index');
		$this->pageTitle ="数独";
		if (empty(Yii::app()->user->id))
			$this->redirect(array('site/loginPage'));
		else
			$this->redirect(array('sudoku/index'));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', array('error'=>$error['message']));
		}
	}

	public function actionLoginPage()
	{
		$this->pageTitle="登录";
		$this->render('loginPage');
	}
	
	public function actionLogin()
	{
		if(isset($_POST['account'])&&isset($_POST['password'])){
			$username=$_POST['account'];
			$password=$_POST['password'];
			$identity=new UserIdentity($username,$password);
			$identity->authenticate();
			switch($identity->errorCode)
			{
				case UserIdentity::ERROR_NONE:
						Yii::app()->user->login($identity);
						$this->redirect(array('sudoku/index'));
					break;
				
				case UserIdentity::ERROR_USERNAME_INVALID:
						$error='用户名错误';
						$this->render('error', array('error'=>$error));
					break;
					
				case UserIdentity::ERROR_PASSWORD_INVALID:
						$error='密码错误';
						$this->render('error', array('error'=>$error));
					break;
					
				default:
						$error='未定义错误';
						$this->render('error', array('error'=>$error));
					break;
			}
		}
	}
	
	public function actionLogout()
	{
		if (!empty(Yii::app()->user->id))
			Yii::app()->user->logout();
		$this->redirect(array('site/loginPage'));
	}
	
	public function actionRegistNewUser()
	{
		if (empty($_POST['account'])||empty($_POST['password'])||empty($_POST['repeatPassword'])||empty($_POST['name'])||empty($_POST['mail']))
		{
			$error='请填写完整信息!';
			$this->render('error', array('error'=>$error));
			return;
		}
		
		$newUser=new User;
		$newUser->account=$_POST['account'];
		if ($_POST['password']!=$_POST['repeatPassword'])
		{
			$error='两次输入密码不一致';
			$this->render('error', array('error'=>$error));
			return;
		}
		
		$user=User::model()->findByAttributes(array(
			'account' => $_POST['account'],
		));
		if (!empty($user))
		{
			$error='用户名已存在';
			$this->render('error', array('error'=>$error));
			return;
		}
		
		$newUser->password=strtoupper(md5($_POST['password']));
		
		//普通权限
		$newUser->privilege=0;
		$newUser->status=1;
		$newUser->mail=$_POST['mail'];
		$newUser->name=$_POST['name'];
		$newUser->sex=$_POST['sex'];
		if ($newUser->save()>0)
		{
			$username=$_POST['account'];
			$password=$_POST['password'];
			$identity=new UserIdentity($username,$password);
			$identity->authenticate();
			Yii::app()->user->login($identity);
			$this->redirect(array('sudoku/index'));
		}else
		{
			$error='未定义错误';
			$this->render('error', array('error'=>$error));
			return;
		}
	}
	
	public function actionRegister()
	{
		$this->pageTitle="登录";
		$this->render('registerPage');
	}
	
	public function actionModifyPage()
	{
		$this->render('modifyPage');
	}
	
	public function actionModifyUser()
	{
		if (empty($_POST['uid'])||empty($_POST['name'])||empty($_POST['mail']))
		{
			$error='请填写完整信息!';
			$this->render('error', array('error'=>$error));
			return;
		}
		
		$newUser=User::model()->findByPk($_POST['uid']);
		
		if (!empty($_POST['password']))
		{
			if ($_POST['password']!=$_POST['repeatPassword'])
			{
				$error='两次输入密码不一致';
				$this->render('error', array('error'=>$error));
				return;
			}
			$newUser->password=strtoupper(md5($_POST['password']));
		}
		
		$newUser->mail=$_POST['mail'];
		$newUser->name=$_POST['name'];
		if (isset($_POST['modify']))
		{
			if ($newUser->save()>0)
			{
				$this->redirect(array('site/usermanagepage'));
			}else
			{
				$error='未定义错误';
				$this->render('error', array('error'=>$error));
				return;
			}
		}else if(isset($_POST['delete'])){
			if ($newUser->delete()>0)
			{
				$this->redirect(array('site/usermanagepage'));
			}else
			{
				$error='未定义错误';
				$this->render('error', array('error'=>$error));
				return;
			}
		}
	}
	
	public function actionModifySelf()
	{
		if (empty($_POST['uid'])||empty($_POST['name'])||empty($_POST['mail']))
		{
			$error='请填写完整信息!';
			$this->render('error', array('error'=>$error));
			return;
		}
		
		$newUser=User::model()->findByPk(Yii::app()->user->id);
		
		if (!empty($_POST['password']))
		{
			if ($_POST['password']!=$_POST['repeatPassword'])
			{
				$error='两次输入密码不一致';
				$this->render('error', array('error'=>$error));
				return;
			}
			$newUser->password=strtoupper(md5($_POST['password']));
		}
		
		$newUser->mail=$_POST['mail'];
		$newUser->name=$_POST['name'];
		$newUser->sex=$_POST['sex'];
		if (isset($_POST['modify']))
		{
			if ($newUser->save()>0)
			{
				$this->redirect(array('site/index'));
			}else
			{
				$error='未定义错误';
				$this->render('error', array('error'=>$error));
				return;
			}
		}else if(isset($_POST['delete'])){
			if ($newUser->delete()>0)
			{
				if (!empty(Yii::app()->user->id))
					Yii::app()->user->logout();
				$this->redirect(array('site/loginPage'));
			}else
			{
				$error='未定义错误';
				$this->render('error', array('error'=>$error));
				return;
			}
		}
	}
	
	public function getMenu()
	{
		$menu='';
		$menuHead='<ul class="nav navbar-nav">';
		$messageMenu='<li class="dropdown">
			<a href="#" class="dropdown-toggle active" data-toggle="dropdown"><span class="badge"></span>我的数独<b class="caret"></b></a>
			<ul class="dropdown-menu">
				<li><a href="'.(Yii::app()->request->baseUrl).'/sudoku/fighting">正在激战<span class="badge"></span></a></li>
				<li><a href="'.(Yii::app()->request->baseUrl).'/sudoku/sudokulistpage">狙击名单</a></li>
				<li><a href="'.(Yii::app()->request->baseUrl).'/sudoku/randomgame">随机来一把</a></li>
				<li><a href="'.(Yii::app()->request->baseUrl).'/sudoku/solve">给Wo出个难题</a></li>
			</ul>
		</li>';
		
		$systemMenu='<li class="dropdown">
			<a href="#" class="dropdown-toggle" data-toggle="dropdown">系统管理<b class="caret"></b></a>
			<ul class="dropdown-menu">
				<li><a href="'.(Yii::app()->request->baseUrl).'/site/usermanagepage">用户管理</a></li>
				<li><a href="'.(Yii::app()->request->baseUrl).'/sudoku/sudokumanagepage">数独管理</a></li>
			</ul>
		</li>';
		
		$userMenu=
		'<ul class="nav navbar-nav navbar-right">
				<li class="dropdown">
					<a href="#" class="dropdown-toggle" data-toggle="dropdown">'.Yii::app()->user->name.'<b class="caret"></b></a>
					<ul class="dropdown-menu">';
		
		if (!empty(Yii::app()->user->id))
		{
				$userMenu=$userMenu.'<li><a href="'.(Yii::app()->request->baseUrl).'/site/modifypage">个人信息修改</a></li>
						<li><a href="'.(Yii::app()->request->baseUrl).'/site/logout">登出</a></li>';
		}
		$userMenu=$userMenu.'</ul>
								</li>
							 </ul>';
		
		$menuEnd='</ul>';
		if (!empty(Yii::app()->user->id))
		{
			$menu=$menuHead.$messageMenu.$menuEnd.$userMenu;
			$priv=User::model()->findByPk(Yii::app()->user->id);
			if (!empty($priv))
			{
				$priv=$priv->privilege;
				if ($priv==2)
					$menu=$menuHead.$messageMenu.$menuEnd.$userMenu;
				if ($priv==3)
					$menu=$menuHead.$messageMenu.$systemMenu.$menuEnd.$userMenu;
			}
		}
		return $menu;
	}
	
	public function actionUserManagePage()
	{
		$priv=User::model()->findByPk(Yii::app()->user->id)->privilege;
		if ($priv==3)
		{
			$this->render('userManagePage');
		}else{
			$error='权限错误';
			$this->render('error', array('error'=>$error));
		}
	}
	
	public function actionGetUserList($status,$keyword)
	{
		$condition=array();
		if (!empty($_GET['keyword']))
				$condition['name']=$_GET['keyword'];
		
		$userList=User::model()->findAllByAttributes(
											$condition
										);
		$res='<ul class="pagination"><li><a href="#" onclick="refreshList()">刷新</a></li>';
		for ($i=0;$i<count($userList)/10;$i++)
		{
		  $res=$res.'<li><a href="#" onclick="goPage('.($i+1).')">'.($i+1).'</a></li>';
		}
		$res=$res.'</ul>';
		echo $res;
		$list='
				<script>userCount='.count($userList).'</script>
				<table class="table table-hover">
				<tr>
					<td>#</td>
					<td>名字</td>
					<td>邮箱地址</td>
			    </tr>';
		for ($i=0;$i<count($userList);$i++)
		{
			if ($i<=9)
			{
				$list=$list.'<tr id="listT'.$i.'T">';
			}else{
				$list=$list.'<tr id="listT'.$i.'T"style="display:none">';
			}
			$list=$list.'<td>'.($i+1).'</td>'
			.'<td><a href="#" data-toggle="modal" data-target="#detailModal" onclick="getUserDetail('.$userList[$i]->user_id.')">'.$userList[$i]->name.'</a></td>'
			.'<td>'.$userList[$i]->mail.'</td>';
		}
		if (count($userList)==0)
		{
			$list=$list.'<tr><td style="text-align:center" colspan="5">暂无数据</td></tr></table>'.'<tr><td colspan="5"><a class="btn btn-success" style="" href="'.Yii::app()->baseUrl.'/site/register">新增</a></td></tr></table>';
		}else{
			$list=$list.'<tr><td colspan="5"><a class="btn btn-success" style="" href="'.Yii::app()->baseUrl.'/site/register">新增</a></td></tr></table>';
		}
		echo $list;
	}
	
	public function actionViewUserDetail($uid)
	{
		$user=User::model()->findByPk($uid);
		if (empty($user))
		{
			$res=
			'<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				<h4 class="modal-title" id="myModalLabel">错误</h4>
			</div>
			<div class="modal-body">
				<div class="container">
					<div class="form-group">
						<h1>未找到该用户！</h1>
					</div>
				</div>
			</div>';
			echo $res;
			return;
		}
		
		$res='<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
			<h4 class="modal-title" id="myModalLabel">用户信息</h4>
		</div>
		<div class="jumbotron">
		<form action="'.Yii::app()->request->baseUrl.'/site/modifyUser" method="post" accept-charset="utf-8" role="form">
			<div class="container">
				<h2>修改信息</h2>
				<table class="table">  
					<tbody>
					<tr>
						<td><input type="text" id="uid" name="uid" value="'.$user->user_id.'" style="display:none"></td>
					</tr> 
					<tr>
						<td><input type="password" name="password" class="form-control" placeholder="修改密码请填写，否则请留空"></td>
					</tr>  
					<tr>
						<td><input type="password" name="repeatPassword" class="form-control" placeholder="再次输入密码"></td>
					</tr>
					<tr>
						<td><input type="text" name="name" value="'.$user->name.'" class="form-control" placeholder="姓名" required=""></td>
					</tr>
					<tr>
						<td><input type="text" name="mail" value="'.$user->mail.'"class="form-control" placeholder="电子邮箱" required="" pattern="^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$" title="邮箱正确格式：xxx@xxx.xxx"></td>
					</tr>
					<tr>
						<td>
							<select id="sex" name="sex" class="form-control" placeholder="性别">
								<option value="0"'.(($user->sex==0)?'selected':'').'>男</option>
								<option value="1"'.(($user->sex==1)?'selected':'').'>女</option>
							</select>
						</td>
					</tr>
					<tr>
						<td>
							<select id="privilege" name="privilege" class="form-control" placeholder="权限">
								<option value="0"'.(($user->privilege==0)?'selected':'').'>访客</option>
								<option value="1"'.(($user->privilege==1)?'selected':'').'>普通用户</option>
								<option value="2"'.(($user->privilege==2)?'selected':'').'>管理员</option>
								<option value="3"'.(($user->privilege==3)?'selected':'').'>超级管理员</option>
							</select>
						</td>
					</tr>
					<tr>
						<td><input name="modify" class="btn btn-primary" type="submit" role="button" value="修改"></td>
						<td>
							<div class="btn-group">
							  <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown">
								删除<span class="caret"></span>
								<span class="sr-only">Toggle Dropdown</span>
							  </button>
							  <ul class="dropdown-menu"  style="min-width:0px;padding:0 0 0 0;" role="menu">
								<li><input name="delete" class="btn btn-danger" type="submit" role="button" value="确认删除"></li>
							  </ul>
							</div>
						</td>
						<td><a class="btn btn-success" data-dismiss="modal" aria-hidden="true" role="button">返回</a></td> 
					</tr>  
				</tbody></table>
			</div>
		</form>
		</div>';
		
		echo $res;
	}
	
}